import axios from 'axios';

// 配置axios基础URL
axios.defaults.baseURL = 'http://localhost:8080';

console.log('🔍 测试管理后台API修复...');
console.log('='.repeat(60));

async function testAdminAPI() {
  try {
    // 1. 测试获取模型列表
    console.log('📋 1. 测试获取模型列表...');
    const listResponse = await axios.get('/api/v2/model/list?page=1&size=5');
    console.log('✅ 获取模型列表成功');
    console.log(`   状态码: ${listResponse.status}`);
    console.log(`   数据条数: ${listResponse.data.data?.data?.length || 0}`);
    
    if (listResponse.data.data?.data?.length > 0) {
      const firstModel = listResponse.data.data.data[0];
      console.log(`   第一个模型: ${firstModel.MName} (ID: ${firstModel.MId})`);
      
      // 检查新字段是否存在
      const newFields = ['MModelSource', 'MBoneBinding', 'MPhysicsBinding', 'MExpressionMaking'];
      const missingFields = newFields.filter(field => !(field in firstModel));
      
      if (missingFields.length === 0) {
        console.log('✅ 新字段存在:', newFields.join(', '));
      } else {
        console.log('⚠️ 缺少字段:', missingFields);
      }
    }

    // 2. 测试添加模型（JSON格式）
    console.log('\n📝 2. 测试添加模型（JSON格式）...');
    const addData = {
      modelId: 0,
      modelName: '测试模型_' + Date.now(),
      modelOccupation: 'bladePoint',
      modelUrl: 'https://example.com/test.zip',
      modelImg: 'https://example.com/test.jpg',
      modelSource: '游戏内提取',
      boneBinding: '已绑定',
      physicsBinding: '已绑定',
      expressionMaking: '已制作'
    };
    
    const addResponse = await axios.post('/api/v2/model/add', addData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    if (addResponse.data.code === 200) {
      console.log('✅ 添加模型成功');
      console.log(`   响应: ${addResponse.data.msg}`);
      
      // 3. 测试更新模型
      console.log('\n✏️ 3. 测试更新模型...');
      const updateData = {
        ...addData,
        modelName: '更新的测试模型_' + Date.now(),
        modelSource: '官方发布',
        boneBinding: '部分绑定'
      };
      
      const updateResponse = await axios.post('/api/v2/model/update', updateData, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      if (updateResponse.data.code === 200) {
        console.log('✅ 更新模型成功');
        console.log(`   响应: ${updateResponse.data.msg}`);
      } else {
        console.log('❌ 更新模型失败');
        console.log(`   错误: ${updateResponse.data.msg}`);
      }
    } else {
      console.log('❌ 添加模型失败');
      console.log(`   错误: ${addResponse.data.msg}`);
    }

    // 4. 测试Content-Type验证
    console.log('\n🔧 4. 测试Content-Type验证...');
    try {
      const wrongContentTypeResponse = await axios.post('/api/v2/model/add', addData, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });
      console.log('⚠️ 使用错误的Content-Type仍然成功（可能后端配置了自动转换）');
    } catch (error) {
      if (error.response?.status === 415) {
        console.log('✅ Content-Type验证正确，415错误被正确返回');
      } else {
        console.log('❌ 意外的错误:', error.message);
      }
    }

  } catch (error) {
    console.log('❌ 测试失败:', error.message);
    if (error.response) {
      console.log(`   状态码: ${error.response.status}`);
      console.log(`   响应数据:`, error.response.data);
    }
  }
}

// 运行测试
testAdminAPI().then(() => {
  console.log('\n' + '='.repeat(60));
  console.log('🎉 测试完成');
}).catch(console.error);
